<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_hb_oil_subsidy')){
    class Api_hb_oil_subsidy extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Hdoilsubsidycustomermodel','m_customer');
            $this->load->model('Hdoilsubsidycitymodel','m_city');
            $this->load->model('configmodel','m_config');

            $this->load->database();


            $game_deadline = $this->m_config->getConfig(HD_OIL_SUBSIDY_DEADLINE);
            if(!empty($game_deadline) && strtotime($game_deadline) < time()) {
                $this->response->setDetail('活动已结束!');
                $this->response->responseExit();
            }

            // $this->_action = $this->uri->rsegments[1].'/'.$this->uri->rsegments[2];
            // if($this->session->userdata($this->_action) !== false) {
            //     $this->response->setDetail('请求太快，请稍后再试!');
            //     $this->response->responseExit();
            // }
            // $this->session->set_userdata($this->_action,true);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
            $info = $this->input->post();
            $this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                // 'customer_id' => $this->m_app->getCurrentCustomerId(),
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info),
                'result_data' => '',
                'api_log_time_create' => NOW,
                // 'terminal' => TERMINAL_WEIXIN,
            ));
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);


            
            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $customer['nickname'] = urldecode($customer['nickname']);
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $this->session->set_userdata('hd_oil_subsidy_customer',$customer);

            $city_list = $this->m_city->getActiveCityList();

            $city_data = array();
            foreach ($city_list as $key => $value) {
            	$city_data[] = array(
            		'city_id' => $value['city_id'],
            		'city_name' => $value['city_name'],
            		'city_available_count' => $value['city_person_money'] > 0 ? intval($value['city_total_money']/$value['city_person_money']) : 0,
            	);
            }
            

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
                'city_data' => $city_data,
            ));
            $this->response->responseExit();
        }

        public function startGame() {
        	$customer = $this->session->userdata('hd_oil_subsidy_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $this->validate->setRule('city_id','integer');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $city = $this->m_city->getCity($info['city_id']);
            if(empty($city) || $city['city_status'] != STATUS_ACTIVE) {
            	$this->response->setDetail('城市错误!');
                $this->response->responseExit();
            }

            $history_id = $this->m_customer->createHistory(array(
            	'customer_id' => $customer['customer_id'],
            	'city_id' => $city['city_id'],
            	'history_status' => STATUS_DELETE,
            	'history_time_create' => NOW,
            ));

            $this->session->set_userdata('hd_oil_subsidy_history_id',$history_id);

            $this->response->setSuccess();
            $this->response->setAddon(array(
                'code' => md5($history_id.SALT),
            ));
            $this->response->responseExit();
        }

        public function endGame() {
        	$customer = $this->session->userdata('hd_oil_subsidy_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $this->validate->setRule('city_id','integer');
            $this->validate->setRule('click_times','integer');
            $this->validate->setRule('code','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $hd_oil_subsidy_history_id = $this->session->userdata('hd_oil_subsidy_history_id');
            $this->session->unset_userdata('hd_oil_subsidy_history_id');
            if($hd_oil_subsidy_history_id === false || md5($hd_oil_subsidy_history_id.SALT) != $info['code']) {
            	$this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $city = $this->m_city->getCity($info['city_id']);
            if(empty($city) || $city['city_status'] != STATUS_ACTIVE || $city['city_id'] != $info['city_id']) {
            	$this->response->setDetail('城市错误!');
                $this->response->responseExit();
            }

            $history = $this->m_customer->getHistory($hd_oil_subsidy_history_id);
            if(empty($history) || $history['history_status'] != STATUS_DELETE) {
            	$this->response->setDetail('你已经提交过!');
                $this->response->responseExit();
            }

            if($info['click_times'] > intval($city['city_time']) * 20) {
            	$this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $gift_money = 0;
            if($customer['gift_money'] == 0 && $info['click_times'] >= $city['city_click_limit']) {
            	$use_money = $this->m_customer->getMoneyFromHistory($city['city_id']);
            	if($use_money <= $city['city_total_money'] - $city['city_person_money']) {
            		$gift_money = $city['city_person_money'];
            	}
            }

            

            if(time() - strtotime($history['history_time_create']) > $city['city_time'] + 10) {
            	$this->response->setDetail('时间间隔过多!');
                $this->response->responseExit();
            }

            $this->m_customer->editHistory(array(
            	'history_id' => $hd_oil_subsidy_history_id,
            	'history_click_time' => $info['click_times'],
            	'gift_money' => $gift_money,
            	'history_status' => $gift_money > 0 ? STATUS_ACTIVE : STATUS_DISABLE,
            	'history_time_submit' => NOW,
            ));

            if($gift_money > 0) {
            	$this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'gift_money' => $gift_money,
                    'customer_time_lottery' => NOW,
                ));
            }
            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);
            $this->session->set_userdata('hd_oil_subsidy_customer',$customer);

            $this->response->setSuccess();
            $this->response->setAddon(array(
                'gift_money' => $gift_money,
            ));
            $this->response->responseExit();
        }

        public function dbview() {
            // die();
            $data['desc'] = '清除戳戳乐数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }

        public function clearDb(){
            // die();
            $this->db->truncate('hd_oil_subsidy_customer'); 
            $this->db->truncate('hd_oil_subsidy_history'); 
            

            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }
    }
    
}